package com.smmisia.wx.handler;

import com.smmisia.wx.config.SparkManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler {

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SparkManager sparkManager;

    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到文本消息事件");
        String content = messageMap.get("Content");
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        if (KEY_WORD.equals(content)) {
            Random random = new Random();
            int num = random.nextInt(1000000);
            String numKey = LOGIN_PREFIX + String.valueOf(num);
            redisTemplate.opsForValue().set(numKey,fromUserName, 5L, TimeUnit.MINUTES);
            String numContent = "您当前的验证码是：" + num + "！ 5分钟内有效";
            String replyContent = "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "  <CreateTime>12345678</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA[" + numContent + "]]></Content>\n" +
                    "</xml>";
            return replyContent;
        }
        String sent = sparkManager.sendMesToAIUseXingHuo(content);
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + sent + "]]></Content>\n" +
                "</xml>";
        return replyContent;
    }

}
